package com.dy.yunying.biz.controller.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.entity.*;
import com.dy.yunying.api.entity.hongbao.ActivityEventType;
import com.dy.yunying.api.req.WanAppChlReq;
import com.dy.yunying.api.req.WanGameBasePackageReq;
import com.dy.yunying.api.req.znfx.AdAccountDownReq;
import com.dy.yunying.api.resp.AdExternalDictRes;
import com.dy.yunying.api.resp.ChannelManageRes;
import com.dy.yunying.api.resp.ParentGameDataRes;
import com.dy.yunying.api.resp.WanGameRes;
import com.dy.yunying.api.resp.hongbao.MenusVO;
import com.dy.yunying.api.resp.hongbao.NodeParentData;
import com.dy.yunying.api.resp.hongbao.OptionData;
import com.dy.yunying.api.vo.GamePackageManageVO;
import com.dy.yunying.api.vo.ParentGameVO;
import com.dy.yunying.biz.config.YunYingProperties;
import com.dy.yunying.biz.dao.manage.AdRoleUserMapper;
import com.dy.yunying.biz.service.ads.AdExternalDictService;
import com.dy.yunying.biz.service.hongbao.ActivityEventTypeService;
import com.dy.yunying.biz.service.hongbao.PopupNoticeService;
import com.dy.yunying.biz.service.manage.*;
import com.dy.yunying.biz.utils.PingYinUtils;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.admin.api.dto.DeptTree;
import com.pig4cloud.pig.admin.api.entity.SysDept;
import com.pig4cloud.pig.admin.api.feign.RemoteDeptService;
import com.pig4cloud.pig.admin.api.feign.RemoteSysFsUserService;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.admin.api.vo.UserSelectVO;
import com.pig4cloud.pig.api.dto.AdAccountTreeResp;
import com.pig4cloud.pig.api.feign.RemoteAccountService;
import com.pig4cloud.pig.api.util.StringUtils;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.constant.enums.AdRoleGameTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 查询公共下拉列，多选框列表，等
 *
 * @author Administrator
 */
@Log4j2
@RestController
@AllArgsConstructor
@RequestMapping("/select")
public class SelectController {

	@Resource
	private YunYingProperties yunYingProperties;

	@Autowired
	private ChannelManageService channelManageService;


	@Autowired
	private GameService gameService;

	@Autowired
	private ParentGameService parentGameService;

	@Autowired
	private GameChannelPackService gameChannelPackService;

	private final AdRoleUserService adRoleUserService;
	private final RemoteDeptService remoteDeptService;
	private final RemoteAccountService remoteAccountService;
	private final RemoteUserService remoteUserService;
	private final AdRoleUserMapper adRoleUserMapper;
	private final AdRoleGameService adRoleGameService;
	private final WanGameBasePackageService wanGameBasePackageService;
	private final AdExternalDictService adExternalDictService;

	private final PopupNoticeService popupNoticeService;

	private final WanCdkService wanCdkService;

	@Autowired
	private ActivityEventTypeService activityEventTypeService;


	private final ParentGameVersionService parentGameVersionService;

	private final RemoteSysFsUserService remoteSysFsUserService;

	/**
	 * 查询数据报表模块的分包 下拉框
	 */
	@RequestMapping(value = "/queryAppchl")
	public R<List<Map<String, String>>> queryAppchlList(@RequestBody(required = false) WanAppChlReq req) {
		try {
			req = null == req ? new WanAppChlReq() : req;

			R<List<Map<String, String>>> result = new R();

			final PigUser user = SecurityUtils.getUser();
			List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
			// 当前账号及管理的账号
			List<Integer> roleUserIdList = new ArrayList<>();
			if (CollectionUtils.isNotEmpty(ownerRoleUserIds)) {
				roleUserIdList.addAll(ownerRoleUserIds);
			}
			roleUserIdList.add(user.getId());
			req.setUserList(roleUserIdList);

			// 授权的广告账户
			List<String> roleAdAccountList = new ArrayList<>();
			req.setRoleAdAccountList(roleAdAccountList);
			final List<String> accountList2 = remoteAccountService.getAccountList2(ownerRoleUserIds, SecurityConstants.FROM_IN);
			if (ObjectUtils.isNotEmpty(accountList2)) {
				roleAdAccountList.addAll(accountList2);
			}

			// 判断是否管理员
			if (SecurityUtils.getRoles().contains(1)) {
				req.setIsSys(1);
			}


			List<Map<String, String>> appchlList = gameChannelPackService.queryAppchlList(req);
			result.setData(appchlList);
			return result;
		} catch (Exception e) {
			return R.failed();
		}
	}

	/**
	 * 查询CPS数据报表模块的分包 下拉框
	 */
	@RequestMapping(value = "/queryCpsAppchl")
	public R<List<Map<String, String>>> queryCpsAppchlList(@RequestBody(required = false) WanAppChlReq req) {
		try {
			req = null == req ? new WanAppChlReq() : req;

			R<List<Map<String, String>>> result = new R();

			final PigUser user = SecurityUtils.getUser();
			List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
			// 当前账号及管理的账号
			List<Integer> roleUserIdList = new ArrayList<>();
			if (CollectionUtils.isNotEmpty(ownerRoleUserIds)) {
				roleUserIdList.addAll(ownerRoleUserIds);
			}
			roleUserIdList.add(user.getId());
			req.setUserList(roleUserIdList);

			// 判断是否管理员
			if (SecurityUtils.getRoles().contains(yunYingProperties.getRoleId())) {
				req.setIsSys(1);
			}

			List<Map<String, String>> appchlList = gameChannelPackService.queryCpsAppchlList(req);
			result.setData(appchlList);
			return result;
		} catch (Exception e) {
			return R.failed();
		}
	}

	/**
	 * 查询CPS数据报表模块的子渠道 下拉框（）
	 */
	@RequestMapping(value = "/queryCpsSubChl")
	public R<List<Map<String, String>>> queryCpsSubChlList(@RequestBody(required = false) WanAppChlReq req) {

		try {
			req = null == req ? new WanAppChlReq() : req;

			R<List<Map<String, String>>> result = new R();

			final PigUser user = SecurityUtils.getUser();
			List<Integer> ownerRoleUserIds = adRoleUserService.getOwnerRoleUserIds();
			// 当前账号及管理的账号
			List<Integer> roleUserIdList = new ArrayList<>();
			if (CollectionUtils.isNotEmpty(ownerRoleUserIds)) {
				roleUserIdList.addAll(ownerRoleUserIds);
			}
			roleUserIdList.add(user.getId());
			req.setUserList(roleUserIdList);

			// 判断是否管理员
			if (SecurityUtils.getRoles().contains(yunYingProperties.getRoleId())) {
				req.setIsSys(1);
			}
			//req.setCpsParentChannelId(yunYingProperties.getCpsParentChannelId());
			//TODO 当前权限需要关联
			List<Map<String, String>> appchlList = gameChannelPackService.queryCpsSubchlList(req);
			result.setData(appchlList);
			return result;
		} catch (Exception e) {
			return R.failed();
		}
	}


	/**
	 * 子游戏列表下拉框
	 *
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/sonGameList.json")
	public R<List<WanGameDO>> sonGameList(WanGameDO req) {
		List<WanGameDO> data = new ArrayList<WanGameDO>();
		try {
			req.setStatus(Short.parseShort("30"));
			data = gameService.selectWanGameListByCond(req);
			return R.ok(data);
		} catch (Exception e) {
			return R.failed();
		}
	}

	/**
	 * 父游戏列表下拉框
	 *
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/parentGameList.json")
	public R<List<ParentGameDO>> parentGameList(ParentGameDO req) {
		try {
			List<ParentGameDO> data = parentGameService.list(Wrappers.<ParentGameDO>query()
					.lambda().eq(ParentGameDO::getStatus, 1));
			return R.ok(data);
		} catch (Exception e) {
			return R.failed();
		}
	}


	/**
	 * 查询渠道平台类型
	 */
	@RequestMapping(value = "/queryPlatForm")
	public R<List<Map<String, String>>> queryPlatForm(HttpServletRequest req) {
		R<List<Map<String, String>>> result = new R();
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, String>> platFormList = channelManageService.queryPlatForm(map);
		result.setData(platFormList);
		return result;
	}


	/**
	 * 查询主渠道列表
	 *
	 * @return
	 */
//	@SysLog("查询主渠道列表")
	@ApiOperation("查询主渠道列表(hma)")
	@RequestMapping("/getChannelList")
	public R getChannelList(Integer toufangStatus) {
		//todo  是否关联该角色绑定的关键账号 对应的渠道
		LambdaQueryWrapper<ChannelManageDO> queryWrapper = Wrappers.<ChannelManageDO>query().lambda().eq(ChannelManageDO::getIsdelete, Integer.parseInt(CommonConstants.STATUS_NORMAL)).eq(ChannelManageDO::getPid, 0);
		if (null != toufangStatus) {
			queryWrapper = queryWrapper.eq(ChannelManageDO::getToufangStatus, toufangStatus);
		}
		queryWrapper = queryWrapper.orderByDesc(ChannelManageDO::getId);
		List<ChannelManageDO> channelManageDOList = channelManageService.getBaseMapper().selectList(queryWrapper);
		List<ChannelManageRes> channelManageResList = channelManageDOList.stream().map(wanGameDO -> {
			ChannelManageRes channelManageRes = new ChannelManageRes();
			BeanUtils.copyProperties(wanGameDO, channelManageRes);
			return channelManageRes;
		}).filter(v -> StringUtils.isNotBlank(v.getPlatformName())).collect(Collectors.toList());
		return R.ok(channelManageResList);
	}


	/**
	 * 查询子渠道列表
	 *
	 * @return
	 */
	@ApiOperation("查询子渠道列表")
	@RequestMapping("/getSubChannelList")
	public R getSubChannelList(String parentChl) {
		LambdaQueryWrapper<ChannelManageDO> queryWrapper = Wrappers.<ChannelManageDO>query().lambda().eq(ChannelManageDO::getIsdelete, Integer.parseInt(CommonConstants.STATUS_NORMAL))
				.eq(StringUtils.isNotBlank(parentChl), ChannelManageDO::getParentCode, parentChl).orderByDesc(ChannelManageDO::getId);
		List<ChannelManageDO> channelManageDOList = channelManageService.list(queryWrapper);
		List<ChannelManageRes> channelManageResList = channelManageDOList.stream().map(wanGameDO -> {
			ChannelManageRes channelManageRes = new ChannelManageRes();
			BeanUtils.copyProperties(wanGameDO, channelManageRes);
			return channelManageRes;
		}).filter(v -> StringUtils.isNotBlank(v.getPlatformName())).collect(Collectors.toList());
		return R.ok(channelManageResList);
	}


	/**
	 * 有基础包的父游戏列表
	 *
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/parentGameBasePackageList")
	public R parentGameBasePackageList(WanGameBasePackageReq req) {
		req.setCurrent(1L);
		req.setSize(100000L);
		IPage<GamePackageManageVO> page = wanGameBasePackageService.selectWanGameBasePackageList(req);
		List<GamePackageManageVO> data = page.getRecords();
		Set<Long> pgIdSet = data.stream().map(GamePackageManageVO::getPgid).filter(Objects::nonNull).collect(Collectors.toSet());

		List<ParentGameDO> list = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(pgIdSet)) {
			list = parentGameService.listByIds(pgIdSet).stream().filter(item -> item.getStatus() != null && item.getStatus() == 1).collect(Collectors.toList());
		}
		return R.ok(list);
	}


	/**
	 * 有基础包的子游戏列表
	 *
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/sonGameBasePackageList")
	public R sonGameBasePackageList(WanGameBasePackageReq req) {
		req.setCurrent(1L);
		req.setSize(100000L);
		IPage<GamePackageManageVO> page = wanGameBasePackageService.selectWanGameBasePackageList(req);
		List<GamePackageManageVO> data = page.getRecords();
		Set<Long> gameIdSet = data.stream().map(GamePackageManageVO::getGameId).collect(Collectors.toSet());

		List<WanGameDO> sonlist = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(gameIdSet)) {
			sonlist = gameService.list(Wrappers.<WanGameDO>query()
					.lambda().in(WanGameDO::getId, gameIdSet).eq(WanGameDO::getStatus, 30).eq(WanGameDO::getIsdelete, 0).orderByAsc(WanGameDO::getId));
		}
		return R.ok(sonlist);
	}


	/**
	 * 有母包的父游戏列表
	 *
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/parentGameVersionVOList")
	public R parentGameVersionVOList(ParentGameDO req) {
		try {
			List<ParentGameVO> data = parentGameService.versionVOList(req);
			return R.ok(data);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return R.failed();
		}
	}


	/**
	 * 有母包的子游戏列表
	 *
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/sonGameVersionVOList")
	public R sonGameVersionVOList(ParentGameDO req) {
		try {
			List<ParentGameVO> data = parentGameService.versionVOList(req);
			Set<Long> pgIdSet = data.stream().map(ParentGameVO::getId).collect(Collectors.toSet());

			List<WanGameDO> sonlist = new ArrayList<>();
			if (CollectionUtils.isNotEmpty(pgIdSet)) {
				sonlist = gameService.list(Wrappers.<WanGameDO>query()
						.lambda().in(WanGameDO::getPgid, pgIdSet).eq(WanGameDO::getStatus, 30).eq(WanGameDO::getIsdelete, 0).orderByAsc(WanGameDO::getId));

			}
			return R.ok(sonlist);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return R.failed();
		}
	}

	/**
	 * 查询父游戏列表
	 *
	 * @param param
	 * @return
	 */
//	@SysLog("查询父游戏列表")
	@ApiOperation("查询父游戏列表(hma)")
	@RequestMapping("/getParentGameList")
	public R getParentGameList(@RequestBody Map<String, Object> param) {
		LambdaQueryWrapper<ParentGameDO> wrapper = Wrappers.<ParentGameDO>query().lambda().orderByAsc(ParentGameDO::getId);
		Optional<Map<String, Object>> paramOps = Optional.ofNullable(param);
		paramOps.map(e -> e.get("gname")).map(Object::toString).filter(StringUtils::isNotEmpty).ifPresent(e -> wrapper.like(ParentGameDO::getGname, e));
		paramOps.map(e -> e.get("status")).map(e -> (Integer) e).ifPresent(e -> wrapper.eq(ParentGameDO::getStatus, e));
		List<ParentGameDO> parentGameDOList = parentGameService.getBaseMapper().selectList(wrapper);
		List<WanGameRes> wanGameResList = parentGameDOList.stream().map(wanGameDO -> {
			WanGameRes wanGameRes = new WanGameRes();
			BeanUtils.copyProperties(wanGameDO, wanGameRes);
			wanGameRes.setPgid(0L);
			return wanGameRes;
		}).collect(Collectors.toList());
		return R.ok(wanGameResList);
	}


	/**
	 * 查询父游戏列表（带角色游戏权限）
	 *
	 * @return
	 * @author zhuxm
	 */
//	@SysLog("查询角色父游戏列表（带角色游戏权限）")
	@ApiOperation("查询角色父游戏列表（带角色游戏权限）")
	@RequestMapping("/getOwnRoleParentGameList")
	public R getOwnRoleParentGameList() {
		List<Long> idsList = adRoleGameService.getOwnerRolePgIds();
		if (Objects.isNull(idsList) || idsList.size() == 0) {
			return R.ok(Lists.newArrayList());
		}
		LambdaQueryWrapper<ParentGameDO> wrapper = new LambdaQueryWrapper();
		wrapper.gt(ParentGameDO::getStatus, 0).in(ParentGameDO::getId, idsList);
		List<ParentGameDO> list = parentGameService.list(wrapper);
		List<WanGameRes> wanGameResList = list.stream().map(wanGameDO -> {
			WanGameRes wanGameRes = new WanGameRes();
			BeanUtils.copyProperties(wanGameDO, wanGameRes);
			wanGameRes.setPgid(0L);
			return wanGameRes;
		}).collect(Collectors.toList());
		return R.ok(wanGameResList);
	}


	/**
	 * 查询父游戏列表（带角色游戏权限）
	 *
	 * @param req
	 * @return
	 * @author zhuxm
	 */
//	@SysLog("查询角色父游戏列表（带角色游戏权限）")
	@ApiOperation("查询角色父游戏列表（带角色游戏权限）")
	@RequestMapping("/getOwnRoleSonGameList")
	public R getOwnRoleSonGameList(WanGameDO req) {
		//获取所有满足权限要求的子游戏
		List<WanGameDO> list = gameService.listByIds(adRoleGameService.getOwnerRoleGameIds());
		List<WanGameRes> wanGameResList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(list)) {
			for (WanGameDO wanGameDO : list) {
				String pgidsStr = req.getPgids();
				if (StringUtils.isNotBlank(pgidsStr)) {
					String[] pgids = pgidsStr.split(",");
					for (String pgid : pgids) {
						if (wanGameDO.getPgid() != null && wanGameDO.getPgid().compareTo(Long.valueOf(pgid)) == 0) {
							WanGameRes wanGameRes = new WanGameRes();
							BeanUtils.copyProperties(wanGameDO, wanGameRes);
							wanGameRes.setPgid(Long.valueOf(pgid));
							wanGameResList.add(wanGameRes);
						}
					}
					//为空，则取全部子游戏
				} else {
					WanGameRes wanGameRes = new WanGameRes();
					BeanUtils.copyProperties(wanGameDO, wanGameRes);
					wanGameResList.add(wanGameRes);
				}

			}
		}
		if (CollectionUtils.isNotEmpty(wanGameResList)) {
			for (WanGameRes wanGame : wanGameResList) {
				if(StringUtils.isNotBlank(wanGame.getGname())){
					wanGame.setFirstWordsName(PingYinUtils.getPinYinHeadCharToUppercase(wanGame.getGname()));
				}
			}
		}
		return R.ok(wanGameResList);
	}

	/**
	 * 当前用户权限对应的平台账号列表
	 *
	 * @param
	 * @return
	 */
	@RequestMapping("/roleUserList")
	public R getRoleUserList() {
		List<UserSelectVO> resultList = adRoleUserService.getOwnerRoleUsers();
		return R.ok(resultList);
	}

	/**
	 * 获取当前登录用户对应角色集合所关联的投放人集合
	 */
	@Inner
	@RequestMapping("/getUserListByRole")
	public R<List<AdRoleUser>> getUserListByRole(@RequestBody List<Integer> roles) {
//		List<Integer> roles = SecurityUtils.getRoles();
		List<AdRoleUser> list = adRoleUserMapper.selectList(Wrappers.<AdRoleUser>query().lambda().in(AdRoleUser::getRoleId, roles));
		return R.ok(list);
	}


	/**
	 * 查询所属角色投放人对应的树形菜单
	 *
	 * @return
	 */
	@ApiOperation("查询所属角色的投放人对应的部门")
	@RequestMapping("/getInvestorDept")
	public R<List<DeptTree>> getInvestorDept(String deptName) {
		List<DeptTree> list = new ArrayList<>();
		List<UserSelectVO> resultList = adRoleUserService.getOwnerRoleUsers();
		List<Integer> deptArr = new ArrayList<>();
		List<Integer> userIds = resultList.stream().map(userSelectVO -> userSelectVO.getUserId()).distinct().collect(Collectors.toList());
		if (CollectionUtils.isEmpty(userIds)) {
			return R.ok(list);
		}
		R r  = remoteUserService.getDeptIdByIds(SecurityConstants.FROM_IN,userIds);
		if(r.getCode() == CommonConstants.SUCCESS){
			//所有用户列表
			deptArr = (List<Integer>) r.getData();
			String deptIds = null;
//			List<Integer> deptArr = userTenantList.stream().map(SysUserTenant::getDeptId).distinct().collect(Collectors.toList());
			if (CollectionUtils.isNotEmpty(deptArr)) {
				deptIds = deptArr.stream().map(Object::toString).distinct().collect(Collectors.joining(","));
			}
			// 查看账户授权用户  对应的部门信息
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("deptArr", deptIds);
			param.put("deptName", deptName);
			R<List<DeptTree>> deptTree = remoteDeptService.getUserDeptTree(param, SecurityConstants.FROM_IN);
			return deptTree;
		} else {
			return R.ok(list);
		}
	}


	/**
	 * 查询所属角色投放人对应的树形菜单
	 *
	 * @return
	 */
	@ApiOperation("查询所属角色的投放人对应的部门")
	@RequestMapping("/getInvestorDeptList")
	public R<List<SysDept>> getInvestorDeptList(String deptName) {
		List<SysDept> list = new ArrayList<>();
		List<UserSelectVO> resultList = adRoleUserService.getOwnerRoleUsers();
		//2022-02-21 运营反馈广告数据分析表部门下拉显示不全
		// 租户改版后，部门ID从 sys_user_tenant 获取
		List<Integer> deptArr = new ArrayList<>();
		List<Integer> userIds = resultList.stream().map(userSelectVO -> userSelectVO.getUserId()).distinct().collect(Collectors.toList());
		if (CollectionUtils.isEmpty(userIds)) {
			return R.ok(list);
		}
		R r  = remoteUserService.getDeptIdByIds(SecurityConstants.FROM_IN,userIds);
		if(r.getCode() == CommonConstants.SUCCESS){
			//所有用户列表
			deptArr = (List<Integer>) r.getData();
			String deptIds = "";
//			List<Integer> deptArr = userTenantList.stream().map(SysUserTenant::getDeptId).distinct().collect(Collectors.toList());
			if (CollectionUtils.isNotEmpty(deptArr)) {
				deptIds = deptArr.stream().map(Object::toString).distinct().collect(Collectors.joining(","));
			}
			if (StringUtils.isBlank(deptIds)) {
				return R.ok(list);
			}
			// 查看账户授权用户  对应的部门信息
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("deptArr", deptIds);
			param.put("deptName", deptName);
			R<List<SysDept>> deptTree = remoteDeptService.getUserDeptList(param, SecurityConstants.FROM_IN);
			return deptTree;
		} else {
			return R.ok(list);
		}
	}


	/**
	 * 查询所属结束投放人对应的树形菜单
	 *
	 * @return
	 */
	@ApiOperation("查询当前用户可查看的广告账号")
	@RequestMapping("/getAccountList")
	public R<List<AdAccountTreeResp>> getAccountList(@RequestBody AdAccountDownReq record) {
		List<String> userIdArr = Lists.newArrayList();
		Boolean isAdmin = Boolean.FALSE;
		if ("1".equals(record.getIsAll())) {
			isAdmin = Boolean.TRUE;
			userIdArr.add(SecurityUtils.getUser().getId().toString());
		}else{
			// 判断是否管理员
			if (SecurityUtils.getRoles().contains(1)) {
				isAdmin = Boolean.TRUE;
			}
			List<UserSelectVO> resultList = Lists.newArrayList();
			if (!isAdmin) {
				resultList = adRoleUserService.getOwnerRoleUsers();
			}
			if (CollectionUtils.isNotEmpty(resultList)) {
				userIdArr = resultList.stream().map(userSelectVO -> userSelectVO.getUserId().toString()).collect(Collectors.toList());
			} else {
				userIdArr.add(SecurityUtils.getUser().getId().toString());
			}
		}

		String mediaCode = StringUtils.isNotBlank(record.getMediaCode()) ? record.getMediaCode() : "";
		return remoteAccountService.getAccountTreeByUserList(userIdArr, isAdmin, mediaCode, SecurityConstants.FROM_IN);
	}


	/**
	 * 查询游戏授权游戏列表(供角色设置游戏权限的时候使用)
	 *
	 * @return
	 * @Author zhuxm
	 */
//	@SysLog("查询游戏授权-游戏列表")
	@ApiOperation("查询游戏授权-游戏列表")
	@RequestMapping("/getRoleGameList")
	public R getRoleGameList() {
		List<WanGameRes> list = null;
		try {
			list = new ArrayList<>();
			WanGameRes allGameRes = new WanGameRes();
			allGameRes.setId(0L);
			allGameRes.setGname("全部游戏");
			allGameRes.setPgid(0L);
			allGameRes.setType(AdRoleGameTypeEnum.All.getValue());
			allGameRes.setSonlist(null);
			list.add(allGameRes);

			Map<String, Object> param = new HashMap<>();
			param.put("status", 1);//1：正常
			R r = getParentGameList(param);
			if (r.getCode() == CommonConstants.SUCCESS) {
				List<WanGameRes> alllist = (List<WanGameRes>) r.getData();
				list.addAll(alllist);
			}
			if (CollectionUtils.isNotEmpty(list)) {
				for (WanGameRes wanGameRes : list) {
					Long id = wanGameRes.getId();//主游戏id
					//避免全部游戏被覆盖
					if (id.compareTo(0L) != 0) {
						wanGameRes.setType(AdRoleGameTypeEnum.PGID.getValue());
					}

					//查询主游戏id的子游戏列表
					List<WanGameDO> sonlist = gameService.list(Wrappers.<WanGameDO>query()
							.lambda().eq(WanGameDO::getPgid, id).eq(WanGameDO::getStatus, 30).eq(WanGameDO::getIsdelete, 0).orderByAsc(WanGameDO::getId));
					wanGameRes.setSonlist(null);
					if (CollectionUtils.isNotEmpty(sonlist)) {
						List<WanGameRes> newsonlist = sonlist.stream().map(wanGameDO -> {
							WanGameRes res = new WanGameRes();
							BeanUtils.copyProperties(wanGameDO, res);
							res.setPgid(id);
							res.setType(AdRoleGameTypeEnum.GAMEID.getValue());
							return res;
						}).collect(Collectors.toList());
						wanGameRes.setSonlist(newsonlist);
					}

				}
			}
		} catch (Throwable e) {
			log.error("查询游戏授权-游戏列表异常", e);
		}
		return R.ok(list);
	}

	@ApiOperation("查询事件列表")
	@GetMapping("/getEvent")
	public R<List<ActivityEventType>> selectEventList() {
		try {
			return R.ok(activityEventTypeService.selectEventList());
		} catch (Exception e) {
			log.error("查询事件列表-接口：{}", e.getMessage());
			return R.failed("查询事件列表");
		}
	}

	@ApiOperation("SDK面板动态菜单列表")
	@RequestMapping("/selectSdkDynamicMenusTitleList")
	public R<List<String>> selectSdkDynamicMenusTitleList() {
		try {
			return R.ok(popupNoticeService.selectSdkDynamicMenusTitleList());
		} catch (Exception e) {
			log.error("SDK面板动态菜单列表-接口：{}", e.getMessage());
			return R.failed("SDK面板动态菜单列表-接口异常");
		}
	}

	@ApiOperation("根据parentId获取SDK面板动态菜单列表")
	@RequestMapping("/selectSdkDynamicMenusTitleListByParentId")
	public R<List<MenusVO>> selectSdkDynamicMenusTitleList(@RequestParam Long id) {
		try {
			return R.ok(popupNoticeService.selectSdkDynamicMenusTitleListByParentId(id));
		} catch (Exception e) {
			log.error("SDK面板动态菜单列表-接口：{}", e.getMessage());
			return R.failed("SDK面板动态菜单列表-接口异常");
		}
	}


	@ApiOperation("获取游戏渠道")
	@RequestMapping("/selectChannel")
	public R<List<NodeParentData>> selectChannel(String pId) {
		try {
			return R.ok(popupNoticeService.selectChannel(pId));
		} catch (Exception e) {
			log.error("获取游戏主渠道-接口：{}", e.getMessage());
			return R.failed("获取游戏主渠道-接口异常");
		}
	}

	@ApiOperation("根据活动类型获取活动列表")
	@RequestMapping("/selectActityListByType")
	public R<List<OptionData>> selectActityListByType(Integer type) {
		try {
			return R.ok(popupNoticeService.selectActityListByType(type));
		} catch (Exception e) {
			log.error("根据活动类型获取活动列表-接口：{}", e.getMessage());
			return R.failed("根据活动类型获取活动列表-接口异常");
		}
	}

	@ApiOperation("根据代金券来源类型获取活动列表")
	@RequestMapping("/selectActityListByCdkSourceType")
	public R<List<OptionData>> selectActityListByCdkSourceType(Integer cdkSourceType) {
		try {
			return R.ok(wanCdkService.selectActityListByCdkSourceType(cdkSourceType));
		} catch (Exception e) {
			log.error("根据代金券来源类型获取活动列表-接口：{}", e.getMessage());
			return R.failed("根据代金券来源类型获取活动列表-接口异常");
		}
	}
	@ApiOperation("转化目标下拉列表-数据报表")
	@RequestMapping("/selectExternalDict")
	public R selectExternalDict(@RequestBody AdExternalDict req){
		List<AdExternalDict> adExternalDictList = adExternalDictService.list(Wrappers.<AdExternalDict>lambdaQuery()
				.eq(AdExternalDict::getPlatformId,req.getPlatformId()).eq(AdExternalDict::getDeleted,0)
				.groupBy(AdExternalDict::getExternalAction));
		if (CollectionUtils.isNotEmpty(adExternalDictList)) {
			List<AdExternalDictRes> adExternalDictResList = adExternalDictList.stream().map(v -> {
				return new AdExternalDictRes().setPlatformId(v.getPlatformId()).setExternalAction(v.getExternalAction()).setExternalName(v.getExternalName());
			}).collect(Collectors.toList());
			return R.ok(adExternalDictResList);
		}else{
			return R.ok(Lists.newArrayList());
		}
	}
	@ApiOperation("深度转化目标下拉列表-数据报表")
	@RequestMapping("/selectDeepExternalDict")
	public R selectDeepExternalDict(@RequestBody AdExternalDict req){
		List<AdExternalDict> adExternalDictList = adExternalDictService.list(Wrappers.<AdExternalDict>lambdaQuery()
				.eq(AdExternalDict::getPlatformId,req.getPlatformId())
				.eq(StringUtils.isNotBlank(req.getExternalAction()),AdExternalDict::getExternalAction, req.getExternalAction())
				.eq(AdExternalDict::getDeleted,0)
				.groupBy(AdExternalDict::getDeepExternalAction));
		if (CollectionUtils.isNotEmpty(adExternalDictList)) {
			List<AdExternalDictRes> adExternalDictResList = adExternalDictList.stream().map(v -> {
				return new AdExternalDictRes().setPlatformId(v.getPlatformId()).setExternalAction(v.getDeepExternalAction()).setExternalName(v.getDeepExternalName());
			}).filter(v -> StringUtils.isNotBlank(v.getExternalAction())).collect(Collectors.toList());
			return R.ok(adExternalDictResList);
		}else{
			return R.ok(Lists.newArrayList());
		}
	}

	@ApiOperation("投放人绑定广告账户并且激活的的用户")
	@RequestMapping("/bindingUserList")
	public R bindingUserList(){
		return adRoleUserService.bindingUserList();
	}

	@ApiOperation("投放人已激活的用户")
	@RequestMapping("/activationUserList")
	public R activationUserList(){
		return adRoleUserService.activationUserList();
	}


	@ApiOperation("所有cps用户")
	@RequestMapping("/cpsUserList")
	public R cpsUserList(){
		return adRoleUserService.selectCpsUserList();
	}



	@ApiOperation("查询角色父游戏信息列表（带角色游戏权限,版本号）")
	@RequestMapping("/selectOwnRoleParentGameDataList")
	public R<List<ParentGameDataRes>> selectOwnRoleParentGameDataList() {
		List<Long> idsList = adRoleGameService.getOwnerRolePgIds();
		if (Objects.isNull(idsList) || idsList.size() == 0) {
			return R.ok(Lists.newArrayList());
		}
		LambdaQueryWrapper<ParentGameDO> wrapper = new LambdaQueryWrapper();
		wrapper.gt(ParentGameDO::getStatus, 0).in(ParentGameDO::getId, idsList);
		List<ParentGameDO> list = parentGameService.list(wrapper);
		if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(list)) {
			List<ParentGameDataRes> gameDataResList = list.stream().map(game -> {
				ParentGameDataRes gameRes = new ParentGameDataRes();
				gameRes.setPgId(game.getId());
				gameRes.setGname(game.getGname());
				gameRes.setPkName(game.getPkName());
				return gameRes;
			}).collect(Collectors.toList());
			if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(gameDataResList)) {
				List<ParentGameVersionDO> gameVersionList = parentGameVersionService.selectListByPgId(gameDataResList);
				for (ParentGameVersionDO gameVersion : gameVersionList) {
					for (ParentGameDataRes data : gameDataResList) {
						if (data.getPgId().equals(gameVersion.getGameId())) {
							data.setCode(gameVersion.getCode());
						}
					}
				}
			}
			return R.ok(gameDataResList);
		}
		return R.ok();
	}


	@ApiOperation("监控规则：通知用户下拉框")
	@RequestMapping("/fsUserList")
	public R fsUserList(){
		return remoteSysFsUserService.getSysFsUserList(SecurityConstants.FROM_IN);
	}

}
